<?php
/**
* 优惠券模块后台 Controller
*
* 优惠券模块后台 Controller的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/

namespace App\Http\Controllers\Backstage;


use App\Http\Controllers\Controller;
use App\Services\Coupons\CouponsServices;
use App\Services\Tool\ImageProcessor\ImagickTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use App\Services\Coupons\CouponsService;

class CouponsController extends Controller
{
    protected  $couponsServices;
    protected  $imagickTool;
    /**
     * CouponsController constructor.
     */
    public function __construct(CouponsServices $couponsServices,ImagickTool $imagickTool,CouponsService $couponsService)
    {
        $this->couponsServices = $couponsServices;
        $this->imagickTool     = $imagickTool;
        $this->couponsService  = $couponsService;
    }

    /**
     * 新增优惠券页面
     */
    public function getAddcoupons()
    {
        return view('backstage.coupons.addcoupons');
    }

    /**
     * 添加优惠券
     * @param Request $request
     * @return array
     */
    public function postAddcoupons(Request $request){
        $rules=array(
                         'name'              => 'required|string',
                         'desc'              => 'required|string',
                         'channel_id'        => 'required|alpha_num|max:4',
                         'num'               => 'required|integer|min:0',
                         'binding_type'      => 'required|integer|min:0',
                         'price'             => 'required|numeric|min:0',
                         'date-range-picker' => 'required|string|',
                         'coupon_type'       => 'required|integer'
                         );
        $validator  = $this->couponsServices->store($request,$rules);
        $channel_id = trim($request->input('channel_id'));
        $channel    = $this->couponsServices->getChannelByChannelId(strtoupper($channel_id));
        $validator->after(function($validator) use ($channel,$channel_id){
            if(strlen($channel_id)!=4){
                $validator->errors()->add('channel_id', '格式不正确');
            }elseif (isset($channel->state)&&($channel->state==1)) {
                $validator->errors()->add('channel_id', '渠道已存在!');
            }
        });
        if ($validator->fails())
        {
            $request->flash();
            return redirect()->back()->withErrors($validator->errors())->withInput();
        }
        $coupon       = array();
        $name         = trim($request->input('name'));
        $num          = intval(trim($request->input('num')));
        $binding_type = intval(trim($request->input('binding_type')));
        $price        = (double)trim($request->input('price'));
        $desc         = trim($request->input('desc'));
        $date_range   = trim($request->input('date-range-picker'));
        $coupon_type  = trim($request->input('coupon_type'));
        if(!empty($date_range)){
            $time_arr             = explode("-",$date_range);
            $begin_time           = strtotime($time_arr[0]);
            $end_time             = strtotime($time_arr[1])+86400-1;
            $coupon['begin_time'] = $begin_time;
            $coupon['end_time']   = $end_time;
        }
        $coupon['num']          = $num;
        $coupon['name']         = $name;
        $coupon['channel_id']   = strtoupper($channel_id);
        $coupon['price']        = $price;
        $coupon['desc']         = $desc;
        $coupon['binding_type'] = $binding_type;
        $coupon['coupon_type']  = isset($coupon_type) && $coupon_type == 2 ? 2 : 1;
        $res                    = $this->couponsServices->addcoupons($coupon);
        if($res==1){
            // $maps = $this->couponsServices->addChannelMap(['channel_id'  => $coupon['channel_id']],$coupon['coupon_type']);
            return redirect()->back()->with('success_message', '添加成功!');
        }else{
            return redirect()->back()->with('error_message', '添加失败!');
        }
    }

    /**
     * 检查渠道是否已经存在
     * @param Request $request
     * @return mixed
     */
    public function postCheckChannelName(Request $request)
    {
        $name=trim($request->input('name'));
        if(empty($name)){
            $result["state"] = 2;
            $result["message"] = "优惠券名不能为空";
            return response()->json($result);
        }
        $channel=$this->couponsServices->getChannelsByName($name);
        if(empty($channel)){
            $result["state"] = 1;
            $result["message"] = "可用";
            return response()->json($result);
        }else{
            $result["state"] = 2;
            $result["message"] = "已存在";
            return response()->json($result);
        }
    }

    /**
     * 检查渠道id是不是已经存在
     * @param Request $request
     * @return mixed
     */
    public function postCheckChannelId(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }

        }
        $channel_id=trim($request->input('channel_id'));
        $channel=$this->couponsServices->getChannelByChannelId($channel_id);
        if(empty($channel)){
            $result["state"] = 1;
            $result["message"] = "可用";
            return response()->json($result);
        }else{
            $result["state"] = 2;
            $result["message"] = "已存在";
            return response()->json($result);
        }
    }

    /**
     * 查看优惠券使用范围
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getGetUseRange(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }

        }
        $id=intval(trim($request->input('id')));
        $channel=$this->couponsServices->getChannelById($id);
        if(!isset($channel->state)||($channel->state!=1)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }
        return view('backstage.coupons.addCouponUseRange')->with('channel',$channel);
    }
    /**
     * 更新优惠券
     * @param Request $request
     * @return array
     */
    public function postCouponUpdate(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0',
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }

        }
        $id=intval(trim($request->input('id')));
        $channel=$this->couponsServices->getChannelById($id);

        if(!isset($channel)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }
        $coupon          = array();
        $name            = trim($request->input('name'));
        $date_range      = trim($request->input('date-range-picker'));
        $desc            = trim($request->input('desc'));
        $coupon['id']    = $id;
        $coupon['name']  = $name;
        if(!empty($desc)){
            $coupon['desc'] = $desc;
        }
        if(!empty($date_range)){
            $time_arr=explode("-",$date_range);
            $begin_time=strtotime($time_arr[0]);
            $end_time  =strtotime($time_arr[1])+86400-1;
            $coupon['begin_time']=$begin_time;
            $coupon['end_time']=$end_time;
        }
        $update_res=$this->couponsServices->updatecoupons($coupon);
        if($update_res==1){
            return redirect()->back()->with('success_message', '更新成功!');
        }else{
            return redirect()->back()->with('error_message', '更新失败!');
        }
    }

    /**
     * 优惠券列表
     * @param Request $request
     * @return $this
     */
    public function getCouponslist(Request $request){
        $channels=$this->couponsServices->couponslist($request);
        return view('backstage.coupons.couponslist')->with("channels",$channels);
    }

    /**
     * 优惠券已绑定优惠券列表
     * @param Request $request
     * @return $this
     */
    public function getCouponBindingCouponlist(Request $request){
        $bindingchids=$this->couponsServices->getCouponBindingCouponlist($request);
        return view('backstage.coupons.couponslist')->with("channels",$bindingchids);
    }

    /**
     * 查看礼包券已绑定优惠券
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getBindingChIdsStep1(Request $request)
    {
        $rules=array(
            'id' => 'required|string'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=trim($request->input('id'));
        if(empty($id)){
            return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
        }
        $channel=$this->couponsServices->getChannelByChannelId($id);
        if(empty($channel)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }
        if($channel->binding_type==1){
            return redirect()->back()->with('error_message', '请重新修改优惠券绑定类型!');
        }
        $binding_channels=$this->couponsServices->getChannelidbindingByChIds($id);
        return view('backstage.coupons.bindingChIdsStep1')->with('binding_channels',$binding_channels)
                                                         ->with('channel',$channel);
    }

    /**
     * 礼包券绑定单券第1步
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function postBindingChIdsStep1(Request $request)
    {
        $rules=array(
            'channelId' => 'required|string'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=trim($request->input('channelId'));
        if ($validator->fails())
        {
            if($validator->errors()->first('channelId')){
                return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
            }
        }
        $channel=$this->couponsServices->getChannelByChannelId($id);
        if(empty($channel)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }
        if($channel->binding_type==1){
            return redirect()->back()->with('error_message', '请重新修改优惠券绑定类型!');
        }
        $datas=$request->all();
        $sel_channels=array();
        $un_use_channels=array();//渠道不存在，或者是礼包券
        $less_than_channels=array();
        $can_use_channels=array();
        foreach ($datas as $key => $data){
            $data_arr=explode('num_',$key);
            if(sizeof($data_arr)>1){
                $sel_channels[]=(object)array('channel_id'=>$data_arr[1],'num'=>(int)$data);
            }
        }
        foreach ($sel_channels as $sel_channel){
            $sel_channel_id=$sel_channel->channel_id;
            $can_use_channel=$this->couponsServices->canBindingChannelByChannelId($sel_channel_id);
            if($can_use_channel){
                $num=$this->couponsServices->getCanUseCouponNumByChannelId($sel_channel_id);
                if($num<$sel_channel->num){
                    $less_than_channels[]=(object)array('channel_id'=>$sel_channel_id,'num'=>(int)$sel_channel->num);
                }else{
                    $can_use_channels[]=(object)array('channel_id'=>$sel_channel_id,'num'=>(int)$sel_channel->num);
                }
            }else{
                $un_use_channels[]=$sel_channel_id;
            }
        }
        return view('backstage.coupons.bindingChIdsStep2')->with('channel',$channel)
            ->with('can_use_channels',$can_use_channels)
            ->with('un_use_channels',$un_use_channels)
            ->with('less_than_channels',$less_than_channels);
    }

    /**
     * 礼包券绑定单券第2步
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postBindingChIdsStep2(Request $request)
    {
        $rules=array(
            'channelId' => 'required|string'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=trim($request->input('channelId'));
//        if ($validator->fails())
//        {
//            if($validator->errors()->first('channelId')){
//                return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
//            }
//        }
       if(empty($id)){
           return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
       }
        $channel=$this->couponsServices->getChannelByChannelId($id);
        if(empty($channel)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }

        if($channel->binding_type==1){
            return redirect()->back()->with('error_message', '请重新修改优惠券绑定类型!');
        }
        $couponbindingcoupons=$this->couponsServices->getCouponbindingcouponsByCouponId($id);
        if(!empty($couponbindingcoupons)){
            return redirect()->back()->with('error_message', '礼包券已绑定，暂不支持修改!');
        }
        $datas=$request->all();
        $sel_channels=array();
        foreach ($datas as $key => $data){
            $data_arr=explode('_',$key);
            if(sizeof($data_arr)>1){
                $sel_channels[]=(object)array('channel_id'=>$data_arr[1],'num'=>(int)$data);
            }
        }
        $res=$this->couponsServices->bindingChIdsStep2($sel_channels,$id);
        if($res){
            return redirect('/backstage/coupons/couponslist')->with('success_message', '礼包券绑定单券成功!');
        }
        return redirect('/backstage/coupons/binding-ch-ids-step1?id='.$id)->with('error_message', '礼包券绑定单券失败!');
    }
    /**
     *  优惠券绑定页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function getBindingCoupons(Request $request){
        $rules=array(
            'id' => 'required|string'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=trim($request->input('id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
            }
        }
        $channel=$this->couponsServices->getChannelByChannelId($id);
        if(empty($channel)){
            return redirect()->back()->with('error_message', '没有找到对应优惠券!');
        }
        if($channel->binding_type==1){
            return redirect()->back()->with('error_message', '请重新修改优惠券绑定类型!');
        }
        $binding_channels=$this->couponsServices->getChannelidbindingByChIds($id);
        $binding_coupons=$this->couponsServices->SearchCoupons('',1,$channel->channel_id);
        return view('backstage.coupons.bindingCoupon')->with('channel',$channel)
                                                          ->with('binding_coupons',$binding_coupons)
                                                          ->with('binding_channels',$binding_channels);
    }

    /**
     * 礼包优惠券绑定优惠券
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postBindingCoupons(Request $request){
        $input = $request->all();

        if(!isset($input['channel_id'])) return redirect()->back()->with('error_message', '无法获取编号!');
        $channel=$this->couponsServices->getChannelByChannelId($input['channel_id']);
        if(empty($channel)||($channel->state!=1)||($channel->end_time<time())){
            return redirect()->back()->with('error_message', '当前礼包券被删除!');
        }
        $ch_ids=$request->input('ch_id');
        if(!is_array($ch_ids) || count($ch_ids) == 0){
            return redirect()->back()->with('error_message', '请选择礼包券子券!');
        }
        //礼包优惠券渠道绑定普通优惠券渠道
        $channelidbinding=$this->couponsServices->getChannelidbindingByChIds($input['channel_id']);
        if(sizeof($channelidbinding)==0){
            //礼包券绑定表，优惠绑定
            $res=$this->couponsServices->bindingCoupons($ch_ids,$input['channel_id']);
        }
        if(sizeof($channelidbinding)!=0){
            return redirect('/backstage/coupons/binding-ch-ids-step1?id='.$input['channel_id'])->with('error_message', '暂不支持修改!');
        }else{
            if(isset($res)&&($res===true)){
                return redirect('/backstage/coupons/binding-ch-ids-step1?id='.$input['channel_id']);
            }else{
                return redirect()->back()->with('error_message', '绑定失败!');
            }
        }
    }
    /**
     * 读入excel
     * @param Request $request
     * @return mixed
     */
    public function getImport(Request $request){
        return $coupons=$this->couponsServices->import($request);
    }
    public function getBindingCouponDetail()
    {
        return $this->couponsServices;
    }
    /**
     * 检查渠道id是不是已经使用过
     * @param Request $request
     * @return mixed
     */
    public function getCheckchannelid(Request $request){
        $result=$this->couponsServices->checkchannelid($request);
        return Response::json($result);
    }
    /**
     * 优惠劵发放页面
     * @param Request $request
     * @return $this
     */
    public function getIssuing(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=intval($request->input('id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '系统繁忙稍后再试!');
            }
        }
        $channel=$this->couponsServices->issuing($id);
        if(empty($channel)){
            return redirect()->back()->with('error_message', '优惠券不存在!');
        }
        return view('backstage.coupons.issuing')->with("channel",$channel);
    }
    /**
     * 生成excel文件
     * @param Request $request
     * @return mixed
     */
    public function getGeneratexls(Request $request){
        $rules=array(
            'channel_id' => 'required|string|'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $channel_id=trim($request->input('channel_id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('channel_id')){
                return redirect()->back()->with('error_message', '系统繁忙稍后再试！!');
            }
        }
        $result=$this->couponsServices->generatexls($channel_id);
        return Response::json($result);
    }

    /**
     * 获取优惠券详情
     * @param Request $request
     * @return $this
     */
    public function getDetail(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=intval($request->input('id'));
        $channel=$this->couponsServices->getChannelById($id);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }
        }
        if(empty($channel)||($channel->state!=1)){
            return redirect()->back()->with('error_message', '优惠券不存在!');
        }
        return view('backstage.coupons.couponsdetail')->with("channel",$channel);
    }
    /**
     * 删除优惠券
     * @param Request $request
     * @return mixed
     */
    public function postDelete(Request $request){
        $input = $request->all();
        if(!isset($input['channel_id'])) return response()->json(['state' => 2, 'message' => '参数不足']);
        $result=$this->couponsServices->delete($input['channel_id']);
        return response()->json($result);
    }

    /**
     * 优惠资源删除
     * @param Request $request
     * @return mixed
     */
    public function postChannelResDelete(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
        }
        $id=intval($request->input('id'));
        $channel=$this->couponsServices->channelResDelete($id);
        if($channel){
            $result["state"] = 1;
            $result["message"] = "删除成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "删除失败";
            return response()->json($result);
        }
    }

    /**
     * 修改优惠券资源额度
     * @param Request $request
     * @return mixed
     */
    public function postChannelResUpdateQuota(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0',
            'quota' => 'required|Numeric|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
        }
        $id         = intval($request->input('id'));
        $channel_id = $this->couponsServices->get_channel_id_by_map_id($id);
        if(!isset($channel_id)){
            $result["state"] = -2;
            $result["message"] = "现金券不允许修改使用范围";
            return response()->json($result);
        }
        $chan       = $this->couponsServices->getChannelById($channel_id);

        if(isset($chan->coupon_type) && $chan->coupon_type == 2){
            $result["state"] = -2;
            $result["message"] = "现金券不允许修改使用范围";
            return response()->json($result);
        }
        //订单额度
        $quota=doubleval($request->input('quota'));
        $channel=$this->couponsServices->channelResUpdateQuota($id,$quota);
        if($channel){
            $result["state"] = 1;
            $result["message"] = "修改成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "修改失败";
            return response()->json($result);
        }
    }

    /**
     *  优惠券搜索
     * @param Request $request
     * @return array
     */
    public function postCouponsSearch(Request $request){
        $v=array(
            'keyword'=>'required|string',
            'channel_id'=>'required|integer|min:0',
        );
        $validator=$this->couponsServices->store($request,$v);
        if ($validator->fails())
        {
            if ($validator->errors()->first('channel_id')) {
                return redirect()->back()->with('error_message', '系统繁忙，请稍后再试!');
            }
        }
        $keyword=trim($request->input('keyword'));
        $keyword=empty($keyword)?'':$keyword;
        $channel_id=intval($request->input('channel_id'));
        $data=$this->couponsServices->SearchCoupons($keyword,1,$channel_id);
        return array('message'=>'成功','data'=>$data,'state'=>'M00000');
    }
    /**
     * 优惠产品搜索
     * @param Request $request
     * @return array
     */
    public function postResSearch(Request $request){
        $v=array(
            'keyword'=>'required|string',
            'range_type'=>'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$v);
        if ($validator->fails())
        {
            if ($validator->errors()->first('keyword')) {
                $keyword='';
            }
            if ($validator->errors()->first('range_type')) {
                $result["state"] = -2;
                $result["message"] = "搜索范围出错";
                return response()->json($result);
            }
        }else{
            $keyword=trim($request->input('keyword'));
        }
        $range_type=intval(trim($request->input('range_type')));
        switch ($range_type){
            case 1:
                $data=$this->couponsServices->SearchProducts($keyword);
                break;
            case 2:
                $data=$this->couponsServices->SearchCreates($keyword);
                break;
            case 3:
                $data=$this->couponsServices->SearchBrands($keyword);
                break;
            default:
                $data=array();
                break;
        }
        return array('message'=>'成功','data'=>$data,'state'=>'M00000');
    }


    /**
     * 添加优惠券使用范围
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAddUseRange(Request $request){
        $v = [
            'id' => 'required|integer|min:0',
        ];
        $validator=$this->couponsServices->store($request,$v);
        $id=intval($request->input('id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '无法获取编号!');
            }
        }

        $product_ids=$request->input('product_ids');
        $create_ids=$request->input('create_ids');
        $brand_ids=$request->input('brand_ids');
        $range_type=intval($request->input('range_type'));
        $quota=(double)trim($request->input('quota'));
        $quota=empty($quota)?0:$quota;
        $res=$this->couponsServices->addUseRange(array(
                                    'product_ids'=>$product_ids,
                                    'create_ids'=>$create_ids,
                                    'brand_ids'=>$brand_ids,
                                    'id'=>$id,
                                    'quota'=>$quota,
                                    'range_type'=>$range_type
                                    ));
        if($res){
            return redirect()->back()->with('success_message', '添加优惠券使用范围成功!');
        }else{
            return redirect()->back()->with('error_message', '添加优惠券使用范围失败!');
        }
    }

    /**
     * 获取优惠券对应优惠范围
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getChannelUseRange(Request $request){
            $rules=array(
                'id' => 'required|integer|min:0'
            );
            $validator=$this->couponsServices->store($request,$rules);
            $id=intval($request->input('id'));
            if ($validator->fails())
            {
                if($validator->errors()->first('id')){
                    return redirect()->back()->with('error_message', '没有对应编号!');
                }
            }
            $channel=$this->couponsServices->getChannelById($id);
            if(empty($channel)||($channel->state!=1)){
                return redirect()->back()->with('error_message', '优惠券不存在!');
            }
            $channel_maps=$this->couponsServices->getChannelMapsByChannelId($channel->channel_id);
            $resource = $this->couponsServices->get_resource_list_by_channel_id($channel->channel_id);
            return view('backstage.coupons.channelUseRangeList')->with("channel",$channel)
                                                                ->with('channel_maps',$channel_maps)
                                                                ->with('resource',$resource);
        }

    /**
     * 优惠券使用范围更新页面
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getChannelUseRangeDetails(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=intval($request->input('id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '没有对应编号!');
            }
        }
        $channel=$this->couponsServices->getChannelById($id);
        if(!isset($channel)||($channel->state!=1)){
            return redirect()->back()->with('error_message', '优惠券不存在!');
        }

        $channel_maps=$this->couponsServices->getChannelAllMapsByChannelId($channel->channel_id);
        return view('backstage.coupons.couponUseRangeDetail')->with("channel",$channel)
                                                             ->with('channel_maps',$channel_maps);
    }

    /**
     * 优惠券使用范围详情更新
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postChannelUseRangeDetails(Request $request){
        $rules=array(
            'id' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        $id=intval($request->input('id'));
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                return redirect()->back()->with('error_message', '无法获取编号!');
            }
        }
        $product_ids=$request->input('product_ids');
        $create_ids=$request->input('create_ids');
        $brand_ids=$request->input('brand_ids');
        $range_type=intval($request->input('range_type'));
        $quota=(double)trim($request->input('quota'));
        $quota=empty($quota)?0:$quota;
        $res=$this->couponsServices->channelUseRangeUpdate(array(
                                    'product_ids'=>$product_ids,
                                    'create_ids'=>$create_ids,
                                    'brand_ids'=>$brand_ids,
                                    'id'=>$id,
                                    'quota'=>$quota,
                                    'range_type'=>$range_type
                                    ));
        if($res){
            return redirect()->back()->with('success_message', '更新优惠券使用范围成功!');
        }else{
            return redirect()->back()->with('error_message', '更新优惠券使用范围失败!');
        }

    }

    /**
     * 更新优惠卷库存
     * @param Request $request
     * @return mixed
     */
    public function postUpdateStock(Request $request)
    {
        $rules=array(
            'id' => 'required|integer|min:0',
            'num' => 'required|integer|min:0'
        );
        $validator=$this->couponsServices->store($request,$rules);
        if ($validator->fails())
        {
            if($validator->errors()->first('id')){
                $result["state"] = -1;
                $result["message"] = "无法获取编号";
                return response()->json($result);
            }
        }
        $id=intval($request->input('id'));
        $num=intval($request->input('num'));
        $res=$this->couponsServices->updateStock($id,$num);
        if($res){
            $result["state"] = 1;
            $result["message"] = "更新成功";
            return response()->json($result);
        }else{
            $result["state"] = -2;
            $result["message"] = "更新失败";
            return response()->json($result);
        }
    }

    /**
     * 按渠道生成优惠券二维码，并打包成压缩包
     * @param Request $request
     * @return mixed
     */
    public function postCouponsQrImg(Request $request)
    {
        $channel_id=trim($request->input('id'));
        Log::info($request->all());
        if(empty($channel_id)){
            $result["state"] = -1;
            $result["message"] = "系统繁忙稍后再试";
            return response()->json($result);
        }
        $res=$this->couponsServices->couponIdExcel2QrImgByChannelId($channel_id);
        if(!empty($res)){
            $result["state"] = 1;
            $result["message"] = "打包成功";
            $result["zip_url"] = $res;
            return response()->json($result);
        }
        $result["state"] = -1;
        $result["message"] = "打包失败";
        return response()->json($result);
    }

    /**
     * 添加优惠券适用范围
     */
    function addChannelMap(Request $request){
        $input  = $request->all();
        $input['add_type'] = isset($input['add_type']) ? $input['add_type'] : 1;
        if($input['add_type'] == 0){
            $resource = $this->couponsServices->get_resource_list_by_channel_id($input['channel_id']);
            foreach($resource['product_temp'] as $one){
                $input['resource_id'] = $one->product_temp_id;
                $input['price'] = 0;
                $result = $this->couponsServices->add_channel_map($input);
            }

            return response()->json(['state' => 'M00000', 'result' => (object)[],'message' => '成功']);
        }else{
            $result = $this->couponsServices->add_channel_map($input);
            return response()->json($result);
        }

    }

    /**
     * 分发优惠券页面
     */
    function couponToUserView(){
        return view('backstage.coupons.touser');
    }

    /**
     * 分发优惠券
     */
    function couponToUser(Request $request){
        $input  = $request->all();
        if(isset($input['is_push']) && $input['is_push']){
            if(!isset($input['title']) || trim($input['title']) == '' ||
                !isset($input['message_phone']) || trim($input['message_phone']) == '' ||
                !isset($input['message']) || trim($input['message']) == '')
                return ['state' => 'M00001', 'result' => (object)[], 'message' => '请将推送信息填写完整'];
        }
        if(!isset($input['coupon_id']) || !isset($input['user_id']) ||
            count(explode(",",$input['coupon_id'])) != count(explode(",",$input['user_id']))){
            return ['state' => 'M00003', 'result' => (object)[], 'message' => '兑换码个数与用户个数不匹配'];
        }
        $coupon_id = explode(",",$input['coupon_id']);
        $user_id   = explode(",",$input['user_id']);
        $str = '';
        for($a = 0;$a < count($coupon_id); $a++){
            $coupon = $this->couponsService->userUnionCoupons(['user_id' => trim($user_id[$a]),'coupon_id' => trim($coupon_id[$a])]);
            if($coupon['state'] == 'M00000'){
                $input['user_id'] = $user_id[$a];
                $result = $this->couponsServices->send_coupon_to_user($input);
            }else{
                $str .= '[优惠券兑换码:' . trim($coupon_id[$a]) . ',用户:' . trim($user_id[$a]) . '分发失败原因:' . $coupon['message'] . ']';
            }
        }
        $result = mb_strlen($str,'utf-8') > 0 ? ['state' => 'M00001', 'result' => '', 'message' => $str]:
                                                ['state' => 'M00000', 'result' => '', 'message' => '全部发送成功'];
        return response()->json($result);
    }

    /**
     * 优惠券列表
     */
    function couponListFromChannel(Request $request){
        $input  = $request->all();
        $result = $this->couponsServices->coupon_list_from_channel($input);
        if($result['state'] != 'M00000') return $result['message'];
        return view('backstage.coupons.coupon-list-channel')->with('result',$result['result']);
    }
}
